<template>
  <div>
    <el-card class="box-card"
      ><Category
        @categoryIdInfo="categoryIdInfo"
        :flag="isAddOrUpDateAndAttrList"
    /></el-card>
    <el-card class="box-card">
      <!-- 属性值展示页面 -->
      <div v-if="isAddOrUpDateAndAttrList">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="isAddOrUpDateAndAttrList = false"
          :disabled="Object.keys(categoryId).length === 0"
          >添加属性</el-button
        >
        <el-table
          border
          style="width: 100%; margin-top: 20px"
          :data="attrInfoList"
        >
          <el-table-column type="index" label="序号" width="160" align="center">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性名称"
            width="200px"
            align="center"
            ><template slot-scope="{ row }">
              <div>
                {{ row.attrName }}
              </div>
            </template></el-table-column
          >
          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width"
            style="margin-left: 10px"
          >
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="(valueList, index) in row.attrValueList"
                :key="valueList.id"
                style="margin: 0 10px"
                >{{ valueList.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="300px"
            align="center"
          >
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="upDataAttr(row)"
                style="margin-right: 10px"
                >修改</el-button
              >
              <el-popconfirm
                :title="`确定删除${row.attrName}属性吗?`"
                @onConfirm="deleteAttr(row)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加和修改页面 -->
      <div v-if="!isAddOrUpDateAndAttrList">
        <el-form class="demo-form-inline" :inline="true" :model="newAttrInfo">
          <el-form-item label="属性名" style="display: block" prop="attrName">
            <el-input
              placeholder="请输入属性名"
              style="width: 200px"
              v-model="newAttrInfo.attrName"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-plus"
              style="margin-right: 20px"
              @click="addAttrName"
              :disabled="newAttrInfo.attrName.trim() === ''"
              >添加属性值</el-button
            ><el-button @click="cancelAttrInfo">取消</el-button>
          </el-form-item>
        </el-form>
        <el-table border style="width: 100%" :data="newAttrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="160" align="center">
          </el-table-column>
          <el-table-column
            label="属性值名称"
            width="width"
            align="center"
            prop="prop"
          >
            <template slot-scope="{ row, $index }">
              <el-input
                v-if="row.isInputOrSpan"
                v-model="row.valueName"
                placeholder="请输入属性名"
                :ref="$index"
                @blur="toShow($index)"
                @keydown.native.enter="toShow($index)"
                size="mini"
              ></el-input
              ><span
                v-else
                @click="toEdit($index)"
                style="font-size: 16px; display: block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width" align="center">
            <template slot-scope="{ row, $index }">
              <!-- 气泡确认框 -->
              <el-popconfirm
                :title="`确定删除${row.valueName}?`"
                @onConfirm="deleteAttrName($index)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  >删除</el-button
                ></el-popconfirm
              >
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-button
            type="primary"
            :disabled="newAttrInfo.attrValueList.length == 0"
            @click="saveAttrInfo"
            >保存</el-button
          ><el-button @click="cancelAttrInfo">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      // 分类id数据
      categoryId: {},
      // 切换添加/修改页面和显示属性
      isAddOrUpDateAndAttrList: true,
      // 显示或隐藏
      isInputOrSpan: true,
      attrInfoList: [],
      // 新的属性
      newAttrInfo: {
        attrName: '',
        attrValueList: [], // {attrId: 0,id: 0,valueName: '' }
        categoryId: 0,
        categoryLevel: 3 // 因为服务器也需要区分几级id
      }
    }
  },
  mounted() {
    // 方便请求，完成删除
    // this.categoryIdInfo({ category1Id: 1, category2Id: 2, category3Id: 3 })
  },
  methods: {
    // Category子组件触发，携带categoryId
    categoryIdInfo(idInfo) {
      this.categoryId = idInfo
      this.getAttrList()
    },
    // 获取平台属性的数据
    async getAttrList() {
      // 获取平台属性分类属性值
      const result = await this.$api.attr.reqAttrInfoList(this.categoryId)
      if (result.code === 200) {
        this.attrInfoList = result.data
      }
    },
    // 新增属性名
    addAttrName() {
      // 收集input里的数据当内容为空时，提示,并且不创建新的input的
      if (this.newAttrInfo.attrValueList.length > 0) {
        // 创建一个时不进入此判断，直接创建
        if (
          this.newAttrInfo.attrValueList[
            this.newAttrInfo.attrValueList.length - 1
          ].valueName.trim() === ''
        ) {
          this.$refs[this.newAttrInfo.attrValueList.length - 1].focus()
          this.$message.warning('输入有误，请输入正确内容')
          return
        }
      }
      // 创建空的属性值，让用户输入  增加显示input还是span标识
      const newAttrValueList = { valueName: '', isInputOrSpan: true }
      this.newAttrInfo.attrValueList.push(newAttrValueList)
      // 等页面加载完后在获取DOM
      this.$nextTick(() => {
        // 添加输入框后，自动获取节点
        this.$refs[this.newAttrInfo.attrValueList.length - 1].focus()
      })
    },
    // 编辑模式
    toEdit(index) {
      console.log(index)
      this.newAttrInfo.attrValueList[index].isInputOrSpan =
        !this.newAttrInfo.attrValueList[index].isInputOrSpan
      if (this.newAttrInfo.attrValueList[index].isInputOrSpan) {
        this.$nextTick(() => {
          this.$refs[index].focus()
        })
      }
    },
    // 显示模式
    toShow(index) {
      // 收集input里的数据当内容为空时，提示
      if (this.newAttrInfo.attrValueList[index].valueName.trim() === '') {
        this.$message.warning('输入有误，请输入正确内容')
        return
      }
      this.newAttrInfo.attrValueList[index].isInputOrSpan = false
    },
    // 添加属性页面的删除，删除属性值
    deleteAttrName(index) {
      this.newAttrInfo.attrValueList.splice(index, 1)
      this.$message.success('删除成功')
    },
    // 取消attr添加，返回列表页面
    cancelAttrInfo() {
      // 清空newAttrInfo里的数据
      this.newAttrInfo = {
        attrName: '',
        attrValueList: [], // {attrId: 0,id: 0,valueName: '' }
        categoryId: 0,
        categoryLevel: 3
      }
      this.isAddOrUpDateAndAttrList = !this.isAddOrUpDateAndAttrList
      // 重新发起请求
      this.getAttrList()
    },
    // 收集表单数据，保存并向服务器发送请求  {"attrName": "string","attrValueList": [{"valueName": "string"}]}
    async saveAttrInfo() {
      // 整理数据，整理成服务器需要的样子
      this.newAttrInfo.attrValueList.forEach((element) => {
        delete element.isInputOrSpan
      })
      this.newAttrInfo.categoryId = this.categoryId.category3Id
      const result = await this.$api.attr.reqSaveAttrInfo(this.newAttrInfo)
      if (result.code === 200) {
        this.$message.success('保存成功')
        // 清空添加属性数据的表单
        this.newAttrInfo = {
          attrName: '',
          attrValueList: [], // {attrId: 0,id: 0,valueName: '' }
          categoryId: 0,
          categoryLevel: 3 // 因为服务器也需要区分几级id
        }
        this.isAddOrUpDateAndAttrList = true
        // 重新发起请求
        this.getAttrList()
      } else {
        this.$message.warning('保存失败')
        return Promise.reject(new Error('file'))
      }
    },
    // 修改平台属性值
    upDataAttr(row) {
      // 展示修改页面
      this.isAddOrUpDateAndAttrList = !this.isAddOrUpDateAndAttrList
      // 等页面出现后，在加载数据，否则会有布局乱一瞬间
      this.$nextTick(() => {
        // 整理数据 深拷贝
        this.newAttrInfo = cloneDeep(row)
        // 给每个属性值增加 编辑和显示切换标识
        this.newAttrInfo.attrValueList.forEach((element) => {
          // 这样书写也可以给属性值添加flag自动，但是会发现视图不会跟着变化（因为flag不是响应式数据）
          // 因为Vue无法探测普通的新增 property,这样书写的属性并非响应式属性（数据变化视图跟这边）
          // 第一个参数:对象  第二个参数:添加新的响应式属性  第三参数：新的属性的属性值
          this.$set(element, 'isInputOrSpan', false)
        })
      })
    },
    // 删除平台属性值
    async deleteAttr(row) {
      const result = await this.$api.attr.reqDeleteAttr(row.id)
      if (result.code === 200) {
        this.$message.success(`删除${row.attrName}平台属性成功`)
        // 重新请求最新数据
        this.getAttrList()
      }
      // attrName: '分类'
      // attrValueList: Array(3)
      // categoryId: 1
      // categoryLevel: 3
      // id: 37
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
}
</style>
